package com.ysx.user.controller;
import com.ysx.common.pojo.Result;
import com.ysx.common.utils.AppJwtUtil;
import com.ysx.user.dto.LoginDto;
import com.ysx.user.service.ApUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ljh
 * @version 1.0
 * @date 2021/2/22 15:37
 * @description 标题
 * @package com.itheima.admin.controller
 */
@RestController
@RequestMapping("/app")
public class LoginController {

    @Autowired
    private ApUserService apUserService;

    /**
     * 用户登录
     *
     * @param appUser 接收手机和密码以及设备ID
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginDto appUser) {
        //不登录先看看
        if (appUser.getFlag() == 0) {
            //生成令牌
            Map<String, Object> info = new HashMap<>();
            //默认设置为 0
            String token = AppJwtUtil.createToken(0L);
            info.put("token", token);
            return Result.ok(info);
        } else {
            //要登录
            if (StringUtils.isEmpty(appUser.getPhone()) || StringUtils.isEmpty(appUser.getPassword())) {
                return Result.errorMessage("用户名或密码不能为空");
            }
            //校验用户名和密码
            Map<String, Object> info = apUserService.login(appUser);
            if (info == null) {
                return Result.errorMessage("用户名或密码错误");
            }
            return Result.ok(info);
        }

    }

    public static void main(String[] args) {
        String s = DigestUtils.md5DigestAsHex(("admin" + "").getBytes());
        System.out.println(s);
    }
}